package com.woniu.atms.controller.pre;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.atms.Global;
import com.woniu.atms.entity.G5User;
import com.woniu.atms.service.G5UserService;
import com.woniu.atms.util.*;
import com.woniu.atms.vo.pre.user.JwtVO;
import com.woniu.atms.vo.pre.user.UserLoginVO;
import com.woniu.atms.vo.pre.user.UserPageVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;

/**
 * @author 张杰
 * @title: PreUserController 用户管理
 * @projectName g5_atms
 * @description: TODO
 * @date 2022/1/17 14:58
 */
@Api(tags = "用户管理（前台）")
@RestController
@RequestMapping("/api/pre/v1/user")
public class PreUserController {
    @Autowired
    private G5UserService g5UserService;
    @Autowired
    private Audience audience;

    /**
     * 前台用户登录
     *
     * @param g5User 用户信息
     * @return 返回统一响应
     */
    @ApiOperation(value = "用户登录", notes = "校验用户的账号及密码，参数为用户信息")
    @PostMapping("/login")
    public ResponseResult login(@RequestBody G5User g5User) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("account", g5User.getAccount());
        G5User u = g5UserService.getOne(queryWrapper);
        if (u == null && "".equals(g5User.getPassword())) {
            return new ResponseResult(Code.FAIL, "请输入账号和密码！");
        }
        if (u == null) {
            return new ResponseResult(Code.FAIL, "没有该用户！");
        }
        if ("".equals(g5User.getPassword())) {
            return new ResponseResult(Code.FAIL, "密码不能为空！");
        }
        if ("n".equals(u.getStatus())) {
            return new ResponseResult(Code.FAIL, "此账号未激活！");
        }
        if ("n".equals(u.getIsExit())) {
            return new ResponseResult(Code.FAIL, "该账号不存在！");
        }
        if (u.getPassword().equals(g5User.getPassword())) {
            //登陆成功
            return new ResponseResult(JwtUtil.createJwt(u.getId(), u.getAccount(), audience));
        } else {
            return new ResponseResult(Code.FAIL, "密码错误！");
        }
    }

    /**
     * 前台用户注册
     *
     * @param userLoginVO 用户登录视图
     * @return 返回统一响应
     */
    @ApiOperation(value = "用户注册", notes = "校验用户输入的账号、密码、手机号及邮箱，系统生成其余信息，激活状态为未激活，uuid激活码通过发送邮件进行激活，参数用户登录视图")
    @PostMapping("/register")
    public ResponseResult register(@RequestBody UserLoginVO userLoginVO) {
        userLoginVO.getG5User().setVCode(UUID.randomUUID().toString().replaceAll("-", ""));
        if ("".equals(userLoginVO.getG5User().getAccount())) {

            return new ResponseResult(Code.FAIL, "请输入账号！");
        }
        char[] account = userLoginVO.getG5User().getAccount().toCharArray();
        if (account.length < 1 || account.length > 14) {
            return new ResponseResult(Code.FAIL, "账号长度必须在1-14个字符之间！");
        }
        if ("".equals(userLoginVO.getG5User().getPassword())) {
            return new ResponseResult(Code.FAIL, "请输入密码！");
        }
        char[] password = userLoginVO.getG5User().getPassword().toCharArray();
        if (password.length < 6 || password.length > 14) {
            return new ResponseResult(Code.FAIL, "密码长度必须在6-14个字符之间！");
        }
        if ("".equals(userLoginVO.getG5User().getTelephone())) {
            return new ResponseResult(Code.FAIL, "请输入手机号！");
        }
        char[] telephone = userLoginVO.getG5User().getTelephone().toCharArray();
        if (telephone.length != 11) {
            return new ResponseResult(Code.FAIL, "手机号必须是11位数字！");
        }
        if ("".equals(userLoginVO.getG5User().getEmail())) {
            return new ResponseResult(Code.FAIL, "请输入邮箱！");
        }
        String email = userLoginVO.getG5User().getEmail();
        if (email.matches("^(\\w+([-.][A-Za-z0-9]+)*){3,18}@\\w+([-.][A-Za-z0-9]+)*\\.\\w+([-.][A-Za-z0-9]+)*$") == false) {
            return new ResponseResult(Code.FAIL, "邮箱格式不正确！");
        }
        if ("".equals(userLoginVO.getKaptcha())) {
            return new ResponseResult(Code.FAIL, "请输入验证码！");
        }
        //从全局变量获得后台生成验证码
        List<String> str = Global.str.get("code");
        for (int i = 0; i < str.size(); i++) {
            String str1 = str.get(0);
            if (str1.equals(userLoginVO.getKaptcha()) == false) {
                return new ResponseResult(Code.FAIL, "验证码不正确！");
            }
        }
        //通过激活码判断是否为同一乘车人
        QueryWrapper queryWrapper3 = new QueryWrapper();
        queryWrapper3.eq("telephone", userLoginVO.getG5User().getTelephone());
        long p = g5UserService.count(queryWrapper3);
        G5User p1 = g5UserService.getOne(queryWrapper3);
        if (p == 1 && "n".equals(p1.getIsExit())) {
            QueryWrapper queryWrapper4 = new QueryWrapper();
            queryWrapper4.eq("account", userLoginVO.getG5User().getAccount());
            G5User u4 = g5UserService.getOne(queryWrapper4);
            if (u4.getAccount().equals(userLoginVO.getG5User().getAccount())) {
                p1.setAccount(userLoginVO.getG5User().getAccount());
                p1.setPassword(userLoginVO.getG5User().getPassword());
                p1.setTelephone(userLoginVO.getG5User().getTelephone());
                p1.setEmail(userLoginVO.getG5User().getEmail());
                p1.setAvatar("");
                p1.setStatus("n");
                p1.setErrorNum(0);
                p1.setRefundNum(0);
                p1.setIsExit("y");
                p1.setVCode(UUID.randomUUID().toString().replaceAll("-", ""));
                g5UserService.update(p1);
                String to = userLoginVO.getG5User().getEmail();
                String lnk = "http://localhost:8080/api/pre/v1/user/active?vCode=" + p1.getVCode();
                String content = "欢迎:    " + p1.getAccount() + "    注册成为G5用户，您的激活码为：  " + p1.getVCode() + "     请点击链接<a href='" + lnk + "'>激活账号</a>。";
                //设置邮箱标题
                String title = "账号激活";
                g5UserService.update(p1);
                MailUtils.sendMail(to, content, title);
                return ResponseResult.SUCCESS;
            }
            return new ResponseResult(Code.FAIL, "该账号已存在！");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("account", userLoginVO.getG5User().getAccount());
        long u = g5UserService.count(queryWrapper);
        if (u == 0) {
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("telephone", userLoginVO.getG5User().getTelephone());
            long u1 = g5UserService.count(queryWrapper1);
            if (u1 == 0) {
                QueryWrapper queryWrapper2 = new QueryWrapper();
                queryWrapper2.eq("email", userLoginVO.getG5User().getEmail());
                long u2 = g5UserService.count(queryWrapper2);
                if (u2 == 0) {
                    String to = userLoginVO.getG5User().getEmail();
                    String lnk = "http://localhost:8080/api/pre/v1/user/active?vCode=" + userLoginVO.getG5User().getVCode();
                    String content = "欢迎:    " + userLoginVO.getG5User().getAccount() + "    注册成为G5用户，您的激活码为：  "
                            + userLoginVO.getG5User().getVCode() + "     请点击链接<a href='" + lnk + "'>激活账号</a>。";
                    //设置邮箱标题
                    String title = "账号激活";
                    g5UserService.add(userLoginVO.getG5User());
                    MailUtils.sendMail(to, content, title);
                    return ResponseResult.SUCCESS;
                }
                return new ResponseResult(Code.FAIL, "该邮箱号已存在！");
            }
            return new ResponseResult(Code.FAIL, "该手机号已存在！");
        }
        return new ResponseResult(Code.FAIL, "该账号已存在！");
    }

    /**
     * 前台用户激活
     *
     * @param g5User 用户信息
     * @return 返回统一响应
     */
    @ApiOperation(value = "用户激活", notes = "用户接收邮件，点击链接，激活状态改为激活，参数为用户信息用于修改激活状态")
    @RequestMapping("active")
    public ResponseResult active(G5User g5User) {
        G5User u = g5UserService.findUserByVCode(g5User.getVCode());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("v_code", g5User.getVCode());
        G5User u2 = g5UserService.getOne(queryWrapper);
        if ((u.getVCode()).equals(u2.getVCode())) {
            u.setStatus("y");
            u.setIsExit("y");
            g5UserService.update(u);
            return ResponseResult.SUCCESS;
        }
        return new ResponseResult(Code.FAIL, "激活码不匹配！");
    }

    /**
     * 生成验证码
     *
     * @param
     * @param response 响应
     * @throws IOException IO异常
     */
    @ApiOperation(value = "激活页面验证码", notes = "四位字符验证码")
    @GetMapping("getImage/{num}")
    public ResponseResult getImage(HttpServletResponse response, @PathVariable Integer num) throws IOException {
        //生成验证码
        String securityCode = VerifyCodeUtils.getSecurityCode();
        //将验证码放入session
        //session.setAttribute("code", securityCode);
        List<String> str = new ArrayList<>();
        str.add(securityCode);
        Global.str.put("code", str);
        //生成图片
        BufferedImage image = VerifyCodeUtils.createImage(securityCode);
        //输出图片
        ServletOutputStream outputStream = response.getOutputStream();
        //调用工具类
        ImageIO.write(image, "png", outputStream);
        return new ResponseResult(Code.SUCCESS, securityCode);
    }

    /**
     * 前台用户个人信息
     *
     * @param g5User 用户信息
     * @return 返回统一响应
     */
    @ApiOperation(value = "用户个人信息", notes = "用户信息详情页面，参数为用户信息")
    @GetMapping("/info")
    public ResponseResult info(@RequestBody G5User g5User) {
        return new ResponseResult<>(g5UserService.findUserByAccount(g5User.getAccount()));
    }

    /**
     * 根据id查询用户
     *
     * @param g5User 用户信息
     * @return 返回统一响应
     */
    @ApiOperation(value = "用户个人信息", notes = "用户信息详情页面，参数为用户信息")
    @PostMapping("/findById")
    public ResponseResult findById(@RequestBody G5User g5User) {
        return new ResponseResult<>(g5UserService.queryById(g5User.getId()));
    }

    /**
     * 用户信息
     * (分页)
     *
     * @param userPageVO 用户查询视图（筛选条件,起始页,每页条数）
     * @return 返回统一响应
     */
    @ApiOperation(value = "分页查询用户信息", notes = "分页查询用户信息（可设多条件：账号、手机号、邮箱可以模糊条件），参数为用户分页查询视图")
    @GetMapping("/page")
    public ResponseResult page(@RequestBody @Validated UserPageVO userPageVO) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", userPageVO.getG5User().getId());
        map.put("account", userPageVO.getG5User().getAccount());
        map.put("telephone", userPageVO.getG5User().getTelephone());
        map.put("email", userPageVO.getG5User().getEmail());
        map.put("status", userPageVO.getG5User().getStatus());
        map.put("errorNum", userPageVO.getG5User().getErrorNum());
        map.put("refundNum", userPageVO.getG5User().getRefundNum());
        map.put("isExit", userPageVO.getG5User().getIsExit());
        return new ResponseResult<>(this.g5UserService.findByPage(map, userPageVO.getPageNum(), userPageVO.getPageSize()));
    }

    /**
     * 前台用户个人信息修改
     *
     * @param g5User 用户信息
     * @return 返回统一响应
     */
    @ApiOperation(value = "用户个人信息修改", notes = "用户信息修改，参数为用户信息")
    @PostMapping("/update")
    public ResponseResult update(@RequestBody @Validated G5User g5User) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("account", g5User.getAccount());
        long u = g5UserService.count(queryWrapper);
        if (u == 0) {
            g5UserService.update(g5User);
            return ResponseResult.SUCCESS;
        }
        return new ResponseResult(Code.FAIL, "该账号已存在！");
    }

    /**
     * 删除用户
     *
     * @param g5User 用户信息
     * @return 返回统一响应
     */
    @ApiOperation(value = "移除用户", notes = "移除用户，参数为用户（逻辑删除）,只是修改状态")
    @PostMapping("/del")
    public ResponseResult<Void> del(@RequestBody G5User g5User) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", g5User.getId());
        long u = g5UserService.count(queryWrapper);
        G5User u2 = g5UserService.getOne(queryWrapper);
        if (u == 1 && "y".equals(u2.getIsExit())) {
            g5User.setIsExit("n");
            g5User.setStatus("n");
            g5User.setVCode("");
            g5UserService.update(g5User);
            return ResponseResult.SUCCESS;
        }
        return new ResponseResult(Code.FAIL, "该用户不存在！");
    }

    /**
     * 根据token，getId
     *
     * @param jwtVO token
     * @return 返回统一响应
     */
    @PostMapping("/getId")
    public ResponseResult getId(@RequestBody JwtVO jwtVO) {
        int id = JwtUtil.parseJwtForId(jwtVO.getToken(), audience);
        if (id != 0) {
            return new ResponseResult(Code.SUCCESS, "", id);
        }
        return new ResponseResult(Code.FAIL, "", null);
    }

}
